package org.flint.data.structure.trie;

import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.TreeMap;

/**
 * @author flint92
 */
public class Trie {

    private class Node {
        boolean isWord;

        TreeMap<Character, Node> next;

        Node() {
            this(false);
        }

        Node(boolean isWord) {
            this.isWord = isWord;
            this.next = new TreeMap<>();
        }
    }

    private Node root;
    private int size;

    public Trie() {
        this.root = new Node();
        this.size = 0;
    }

    /**
     * 获取单词数量
     *
     * @return 单词数量
     */
    public int getSize() {
        return size;
    }

    /**
     * 向Trie中添加一个新的单词Word
     *
     * @param word 单词
     */
    public void add(String word) {
        if (StringUtils.isBlank(word)) {
            return;
        }
        Node cur = root;
        final char[] chars = word.toCharArray();
        for (char c : chars) {
            if (Objects.isNull(cur.next.get(c))) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        if (!cur.isWord) {
            cur.isWord = true;
            size++;
        }
    }

    /**
     * 查询Trie是否包含单词Word
     *
     * @param word 单词
     * @return bool
     */
    public boolean contains(String word) {
        if (StringUtils.isBlank(word)) {
            return false;
        }
        Node cur = root;
        final char[] chars = word.toCharArray();
        for (char c : chars) {
            if (Objects.isNull(cur.next.get(c))) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 查询是否在Trie中有单词prefix为前缀
     *
     * @param prefix 前缀单词
     * @return bool
     */
    public boolean isPrefix(String prefix) {
        if (StringUtils.isBlank(prefix)) {
            return false;
        }
        Node cur = root;
        final char[] chars = prefix.toCharArray();
        for (char c : chars) {
            if (Objects.isNull(cur.next.get(c))) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }
}
